#include "projectHeader.h"

void* keepAliveTimeOutThread(void* t)
{
	//printf("INSIDE KEEP ALIVE TIMEOUT THREAD.\n");

	
	while(1)
	{
		pthread_mutex_lock(&connectedNodeListMutex);
		pthread_mutex_lock(&sockIndexMapMutex);
		/*
		if(terminate)
		{
			pthread_exit(NULL);
		}
		*/

				map<int,int>:: iterator temp2;
				
				for(temp2=sockFDToQIndexMap.begin();temp2!=sockFDToQIndexMap.end();temp2++)
				{
					int mapIndex=(*temp2).second;
					map<int,int>:: iterator temp3;
					temp3=keepAliveTimers.find(mapIndex);
					int timer=(*temp3).second;
					//printf("\n############################%d----%d############################\n",mapIndex,timer);
					if( timer !=0 )
					{
						timer=timer-1;
						(*temp3).second=timer;
					}
					else
					{
						int socket=(*temp2).first;
						sockFDToQIndexMap.erase(temp2);
						keepAliveTimers.erase(temp3);
						
						//erase from connectedNodeList map
						
						map<string,int>:: iterator temp4;
						for(temp4=connectedNodeList.begin();temp4!=connectedNodeList.end();temp4++)
						{
							if((*temp4).second==socket)
							{
								//printf("\nTimeout for socket : %d... hostString is %s and map socket is : %d....\n",socket,(*temp4).first.c_str(),(*temp4).second);
								connectedNodeList.erase(temp4);
							}
						}

						//pthread_cancel read and write thread.
						pthread_cancel(readBeacon[mapIndex]);
						pthread_cancel(writeBeacon[mapIndex]);	

						//erase from wQueueIndexBitMap map
						//wQueueIndexBitMap.set(mapIndex,0);

						close(socket);
					}
				}
		pthread_mutex_unlock(&sockIndexMapMutex);
		pthread_mutex_unlock(&connectedNodeListMutex);
		usleep(1000000);
	
	}





	pthread_exit(NULL);
	
}
